#include "ranking.h"
#include "ui_ranking.h"
#include "comsettlement.h"
#include "gift.h"
#include <QSqlDatabase> //数据驱动
#include <QSqlQuery> //数据库执行语句
#include <QSqlRecord>
#include <QSqlQueryModel>
#include <QTableView>

Ranking::Ranking(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Ranking)
{
    ui->setupUi(this);
    //设置游戏界面的背景图
    this->setFixedSize(600,450);//固定窗口大小
    QPalette pal =this->palette();
    QImage ImgAllbackground(":/images/background3.jpg");
    QImage fitimpic = ImgAllbackground.scaled(this->width(),this->height(),Qt::IgnoreAspectRatio);
    pal.setBrush(QPalette::Window,QBrush(fitimpic));
    setPalette(pal);
}

Ranking::~Ranking()
{
    delete ui;
}

void Ranking::Init(){
    mysql_init();
}

//数据库初始化
bool Ranking::mysql_init(){
    QSqlDatabase db;
    QString dsn;
    //先判断是否已经连接
    if(QSqlDatabase::contains("qt_sql_default_connection"))
      db = QSqlDatabase::database("qt_sql_default_connection");
    //没有则连接自己的数据库
    else{
      db = QSqlDatabase::addDatabase("QODBC");
      dsn = "Driver={MySQL ODBC 8.0 UniCode Driver};"; // Driver is now {MySQL}
//          dsn.append("Server=192.168.112.132,3306;"); // IP,Port
          dsn.append("Server=192.168.0.196,3306;"); // IP,Port
          dsn.append("Database=calculate24;"); // Schema
          dsn.append("Uid=root;"); // User
          dsn.append("Pwd=1234;"); // Password
          dsn.append("MULTI_HOST=1;");
          db.setDatabaseName(dsn);
    }
    if(!db.open())
    {
        qDebug()<<"open error";
        return false;
    }
    else{
        qDebug()<<"打开成功";
        QSqlQueryModel *model = new QSqlQueryModel;
        model->setQuery("SELECT id,username,highestScore FROM  tb_user order by highestScore desc");
        model->setHeaderData(0, Qt::Horizontal, tr("ID"));
        model->setHeaderData(1, Qt::Horizontal, tr("用户名"));
        model->setHeaderData(2, Qt::Horizontal, tr("最高得分"));
//        QTableView *view = new QTableView(this);
        ui->view->setModel(model);
        ui->view->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        //隐藏行序号
        ui->view->verticalHeader()->hide();

//        QString book_name= model->record(1).value("book_name").toString();//返回第一行字段为book_name的项
        return true;
    }
}

void Ranking::on_back_btn_clicked()
{
    comSettlement::p_settlement->show();
    this->hide();
}

void Ranking::on_gift_clicked()
{
    Gift *g = new Gift(this);
    g->exec();
}
